import numpy as np

def length( v ):
    return np.sqrt(np.dot(v,v))
    
def uv_to_dir( u,v):
    dir = np.array([u, v, np.sqrt(1-u**2-v**2) ])
    return dir

def uv_to_theta_phi( u,v ):
    x,y,z = uv_to_dir(u,v).tolist()
    theta = np.arccos(z)
    phi = np.arctan2(y,x)
    return theta, phi
import string
import random
def id_generator(size=6, chars=string.ascii_lowercase):
    return ''.join(random.choice(chars) for x in range(size))

from ROOT import *

canvases = {}
THs = {}
graphs = {}

def plot_in_TH2F( data, title, bins=(100,100) ):
    x = data[:,0]
    y = data[:,1]
    
    if len(canvases):
        new_key = max(canvases.keys())+1
    else:
        new_key = 1
    c_name = "c"+str(new_key)
    canvases[new_key] = [c_name]
    c = TCanvas( c_name,title,0,0,500,500)
    canvases[new_key].append(c)
    
    if len(THs):
        new_key = max(THs.keys())+1
    else:
        new_key = 1
    h_name = "h"+str(new_key)
    THs[new_key] = [h_name]
    h = TH2F( h_name, title, bins[0],x.min(),x.max(),bins[1],y.min(),y.max())
    THs[new_key].append(h)
    
    for i in data:
        h.Fill(i[0],i[1])

    c.cd()
    h.Draw("colz")
    c.Update()
    return

def plot_in_TH1F( data, title, bins=100 ):
    x = data
    
    if len(canvases):
        new_key = max(canvases.keys())+1
    else:
        new_key = 1
    c_name = "c"+str(new_key)
    canvases[new_key] = [c_name]

    c = TCanvas( c_name,title,0,0,500,500)
    canvases[new_key].append(c)
    
    if len(THs):
        new_key = max(THs.keys())+1
    else:
        new_key = 1
    h_name = "h"+str(new_key)
    THs[new_key] = [h_name]    
    h = TH1F( h_name, title, bins,x.min(),x.max())
    THs[new_key].append(h)
    
    for i in data:
        h.Fill(i)
    
    c.cd()
    h.Draw()
    c.Update()
    return

list_of_fuck=[]
def plot_in_TGraph2D( data, title ):
    #raise NotImplementedError("This function is buggy, so I declare it as not implemented. DN")
    
    if len(canvases):
        new_key = max(canvases.keys())+1
    else:
        new_key = 1
    c_name = "c"+str(new_key)
    canvases[new_key] = [c_name]
    c = TCanvas( c_name,title,0,0,500,500)
    canvases[new_key].append(c)
    
    #if len(graphs):
    #    new_key = max(graphs.keys())+1
    #else:
    #    new_key = 1
    #g_name = "g"+str(new_key)
    #graphs[new_key] = [g_name]
    g = TGraph2D()
    list_of_fuck.append(g)
    #g.SetName(g_name)
    #graphs[new_key].append(g)

    for index,d in enumerate(data):
        g.SetPoint( index, *d)
    
    g.SetMarkerStyle(20)
    g.SetTitle(title)
    
    c.cd()
    g.Draw("pcol")
    c.Update()
    
    return
